import store from '@/store'
import { isLogin } from '@/utils/token'
import Vue from 'vue'
import VueRouter from 'vue-router'
import Admin from '_views/Admin'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'admin',
    component: Admin,
    // 提前定义重定向
    children: [
      {
        path: '/',
        redirect: '/dashBoard'
      }
    ]
  },
  // 登陆页面
  {
    path: '/login',
    name: '登录',
    component: () => import('_views/Login')
  }
  // 404
]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
// 路由前置拦截器，第一步在此判断是否有token
router.beforeEach((to, from, next) => {
  if (to.path !== '/login') {
    if (isLogin()) {
      next()
    } else {
      router.replace('/login')
    }
  } else {
    next()
  }
})
/*
  路由后置守卫，当路由跳转成功，会把它写入navtab
*/
router.afterEach((to) => {
  // 定义一个tab对象用来接收当前路由的名字和路径，作为添加方法ADD_NAV_TAB的参数名字显示在navtab标签中
  const tab = {
    name: to.name,
    path: to.path
  }
  // 提交方法，将对象存储到navtabs【】中
  store.commit('base/ADD_NAV_TAB', tab)
})
export default router
